package forJava;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author hanj.cn@outlook.com
 */
public class Serializable {

    public static void main(String[] args) {

        try (//创建一个ObjectOutputStream输出流
             ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\桌面\\杂物\\object.ser"))) {
            //将对象序列化到文件s
            Person1 person = new Person1("韩杰", 23);
            oos.writeObject(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class Person1 implements java.io.Serializable {

    private String name;
    private int age;

    public Person1(String name, int age) {
        // 不提供无参构造器
        System.out.println("person1的有参构造器被调用...");
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {

        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

}

class ReadObject {

    public static void main(String[] args) {

        try (//创建一个ObjectInputStream输入流
             ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\桌面\\杂物\\object.ser"))) {
            Person1 brady = (Person1) ois.readObject();
            System.out.println(brady);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
